package com.dong.component;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程范围作用域
 *
 * @author Administrator 2021/09/03 14:09
 */
public class MyScope implements Scope {

    private final ThreadLocal<Map<String,Object>> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>());

    @Override
    public Object get(String s, ObjectFactory<?> objectFactory) {
        Map<String,Object> map = threadLocal.get();
        Object obj = map.get(s);
        if (obj == null){
            obj = objectFactory.getObject();
            map.put(s,obj);
            System.out.println("不存在名字为"+s+"的bean：" + obj.hashCode());
        }else{
            System.out.println("存在名字为"+s+"的bean：" + obj.hashCode());
        }
        return obj;
    }

    @Override
    public Object remove(String s) {
        Map<String,Object> map = threadLocal.get();
        return map.remove(s);
    }

    @Override
    public void registerDestructionCallback(String s, Runnable runnable) {

    }

    @Override
    public Object resolveContextualObject(String s) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
